package com.chinasofti.project.web;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chinasofti.project.common.RandomUtils;
import com.chinasofti.project.common.SimpleDigestUtil;
import com.chinasofti.project.common.result.ExecuteResult;
import com.chinasofti.project.components.ParamLoggingInterceptor;
import com.chinasofti.project.dal.model.BzUser;
import com.chinasofti.project.service.user.MailService;
import com.chinasofti.project.service.user.UserService;
import com.chinasofti.project.web.common.ControllerBase;
import com.chinasofti.project.web.form.FindPasswordForm;
import com.chinasofti.project.web.form.LoginForm;
import com.chinasofti.project.web.form.RegisterForm;

@Controller
public class UserController extends ControllerBase {
	private static final Logger logger = LoggerFactory.getLogger(ParamLoggingInterceptor.class);
	@Autowired
	private UserService userService;

	@Autowired
	private MailService mailService;

	/* 登录 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String loginController(HttpServletResponse response, LoginForm loginForm, BindingResult result,
			ModelMap model, HttpSession httpSession) {
		loginForm.validate();
		BzUser bzUser = new BzUser();
		String op = (String) httpSession.getAttribute("OP");

		if (op == null) {
			op = "index.jsp";
		}

		/* 三十天内免密码登录 */
		String cookieUsername = (String) httpSession.getAttribute("username");
		String cookiePassword = (String) httpSession.getAttribute("password");
		if (cookieUsername != null && cookiePassword != null) {
			bzUser.setUserEmail(cookieUsername);
			bzUser.setUserPassword(cookiePassword);
			BzUser cookieBzUserResult = userService.SelectUserEmailAndPassword(bzUser);
			if (cookieBzUserResult != null) {
				model.put("msg", "登录成功");
				int userId = cookieBzUserResult.getUserId();
				int shopNum = userService.selectNumByUserId(userId);
				httpSession.setAttribute("shoppingCartNum", shopNum);
				httpSession.setAttribute("userId", userId);
				httpSession.setAttribute("user", cookieBzUserResult);
				return "index.jsp";
			} else {
				model.put("msg", "免密码登录失效，请重新登录");
				return "login";
			}
		}
		/* 将密码加密并将值copy到BzUser中 */
		String password = loginForm.getUserPassword();
		String loginCheck = loginForm.getLoginCheckbox();
		String encryptedPassword = SimpleDigestUtil.encryptSHA(password);
		loginForm.setUserPassword(encryptedPassword);
		BeanUtils.copyProperties(loginForm, bzUser);
		/* 判断用户名是否存在 */
		String userEmail = loginForm.getUserEmail();
		Boolean haveEmail = userService.queryUserEmail(userEmail);
		if (haveEmail == true) {
			model.put("msg", "该用户名不存在，请重新输入");
			return "login";
		}

		String captcha = (String) httpSession.getAttribute("sessionCaptcha");
		if (!loginForm.getUserCaptcha().equalsIgnoreCase(captcha)) {
			model.put("msg", "验证码不正确，请重新输入");
			return "login";
		}

		BzUser bzUserResult = userService.SelectUserEmailAndPassword(bzUser);
		if (bzUserResult == null) {
			model.put("msg", "账号或密码错误，请重新登录");
			return "login";
		}

		Date nowLogintime = bzUserResult.getUserNowLogintime();
		int userId = bzUserResult.getUserId();
		int row = userService.updateLoginTime(nowLogintime, userId);
		if (row < 1) {
			model.put("msg", "更新时间失败，不影响登录");
			return "redirect:" + op;
		}

		if ("y".equalsIgnoreCase(loginCheck)) {
			Cookie usernameCookie = new Cookie("username", userEmail);
			usernameCookie.setMaxAge(60 * 60);
			response.addCookie(usernameCookie);
			Cookie passwordCookie = new Cookie("password", encryptedPassword);
			passwordCookie.setMaxAge(3600 * 24 * 30);
			response.addCookie(passwordCookie);
		}
		int shopNum = userService.selectNumByUserId(userId);
		httpSession.setAttribute("shoppingCartNum", shopNum);
		httpSession.setAttribute("userId", userId);
		httpSession.setAttribute("user", bzUserResult);
		return "redirect:" + op;
	}

	/* 发送邮件 */
	@RequestMapping("sendEmail")
	@ResponseBody
	private ExecuteResult sendEmail(String userEmail, ModelMap model, HttpSession httpSession) {
		String code = RandomUtils.randomString(4);
		mailService.sendResetPasswordMail(userEmail, code);
		httpSession.setAttribute("resetPasswordValidationCode", code);
		logger.info("======>邮箱验证码{}", code);
		return ExecuteResult.successResult();
	}

	/* 注册 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public String register(RegisterForm registerForm, ModelMap model, HttpSession httpSession) {
		registerForm.validate();
		BzUser bzUser = new BzUser();
		String password = registerForm.getUserPassword();
		String encryptedPassword = SimpleDigestUtil.encryptSHA(password);
		registerForm.setUserPassword(encryptedPassword);
		String userEmail = registerForm.getUserEmail();
		Boolean haveEmail = userService.queryUserEmail(userEmail);
		if (haveEmail == false) {
			model.put("msg", "该用户名已存在，请重新输入");
			return "redirect:toLogin?p=register";
		}
		String captcha = registerForm.getUserCaptcha();
		String sessionCaptcha = (String) httpSession.getAttribute("resetPasswordValidationCode");
		if (!captcha.equals(sessionCaptcha)) {
			model.put("msg", "验证码不正确，请重新输入");
			return "redirect:toLogin?p=register";
		}
		BeanUtils.copyProperties(registerForm, bzUser);
		int row = userService.insertFromRegister(bzUser);
		if (row < 1) {
			model.put("msg", "注册失败，请重新注册");
			return "redirect:toLogin?p=register";
		}
		model.put("msg", "注册成功，请登录");
		return "login";

	}

	/* 找回密码 */
	@RequestMapping(value = "findPassword", method = RequestMethod.POST)
	public String findPassword(FindPasswordForm findPasswordForm, ModelMap model, HttpSession httpSession) {
		findPasswordForm.validate();
		BzUser bzUser = new BzUser();
		String password = findPasswordForm.getUserPassword();
		String encryptedPassword = SimpleDigestUtil.encryptSHA(password);
		findPasswordForm.setUserPassword(encryptedPassword);
		String userEmail = findPasswordForm.getUserEmail();
		Boolean haveEmail = userService.queryUserEmail(userEmail);
		if (haveEmail == true) {
			model.put("msg", "该用户名不存在，请重新输入");
			return "redirect:toLogin?p=resetpwd";
		}
		String captcha = findPasswordForm.getUserCaptcha();
		String sessionCaptcha = (String) httpSession.getAttribute("resetPasswordValidationCode");
		if (!captcha.equals(sessionCaptcha)) {
			model.put("msg", "验证码不正确，请重新输入");
			return "redirect:toLogin?p=resetpwd";
		}
		BeanUtils.copyProperties(findPasswordForm, bzUser);
		int row = userService.updatePassword(bzUser);
		if (row < 1) {
			model.put("msg", "修改密码失败，请重新修改");
			return "redirect:toLogin?p=resetpwd";
		}
		model.put("msg", "修改密码成功，请登录");
		return "login";
	}

	/* 退出 */
	@RequestMapping("SignOut")
	public String signOut(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
		session.removeAttribute("user");
		session.removeAttribute("userId");
		session.invalidate();
		Cookie[] cookies = request.getCookies();
		// 3.遍历删除cookies中的值
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			cookie.setMaxAge(0);
			cookie.setValue(null);
			cookie.setPath(request.getContextPath() + "/");
			response.addCookie(cookie);
		}
		return "redirect:index.jsp";
	}
}
